package friot.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import friot.utils.tools.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 登录验证过滤类
 *
 * @author He Kuntao
 * @date 2023/11/23 11:07
 */
@Slf4j
@Component
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        // 放行Login
        if ("/user/api/account/login".equals(path)) {
            return chain.filter(exchange);
        }

        // 获取 token
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("token");

        // token非空校验
        if (!StringUtils.hasText(token)) {
            // 不存在token直接返回
            log.error("不存在token");
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        // token解密
        try {
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            // token非法或过期
            log.error("token非法或过期");
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }


    /**
     * 优先级设置：值越小，优先级越高
     *
     * @return 优先级值
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
